import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


public class TextFileOpener {
	//we're making a map, OUTSIDE OF THE CONSTRUCTOR! It's gonna hold the counts of dialogue for each pony
	private Map<String, PonyProperties> characterLineCountMap = new HashMap<String, PonyProperties>();

	public TextFileOpener(String textFile){

		BufferedReader br = getOneLineBufferReader(textFile);
		makeLineCounts(br);
		outputLineCounts();
	}

	BufferedReader getOneLineBufferReader(String textFile){
		try{
			FileInputStream fstream = new FileInputStream(textFile);
			// Get the object of DataInputStream
			InputStreamReader in = new InputStreamReader(fstream);
			BufferedReader br = new BufferedReader(in);
			return br;

		}
		catch(IOException e){
			e.printStackTrace();
		}
		return null;
	}

	public void makeLineCounts(BufferedReader lineReader){
		try{
			String strLine = lineReader.readLine();
			//Read File Line By Line
			while (strLine != null)   {
				// Print the content on the console
				//System.out.println (strLine);
				if(strLine.indexOf(':') > 0){


					String ponyName = strLine.substring(0, strLine.indexOf(':'));
					//if the Map has the ponyname as a key, add 1 to the value
					//else, make a key with the ponyname, with a value of 1
					if(characterLineCountMap.containsKey(ponyName)){
						characterLineCountMap.get(ponyName).addLine(strLine.length());
					}
					else{
						PonyProperties currentPonyProperties = new PonyProperties();
						currentPonyProperties.addLine(strLine.length());
						characterLineCountMap.put(ponyName, currentPonyProperties);
						//System.out.println(ponyName);
					}
				}
				strLine = lineReader.readLine();
			}
			lineReader.close();
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}

	public void outputLineCounts(){
		for(Map.Entry<String, PonyProperties> a: characterLineCountMap.entrySet()){
			String ponyName = a.getKey();
			int ponyLineCount = a.getValue().getNumberOfLines();
			
			System.out.println(ponyName + ": " + ponyLineCount + ", and the average number of characters is: " + a.getValue().getNumberOfAverageCharactersPerLine());
		}
	}


}
